﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using COFE.Core;
using COFE.Core.Profile;

namespace COFE.Helpers
{
    public static class COFEAdmin
    {
        #region Methods

        internal static IUserProfileManager2 checkUpm()
        {
            if (COFEShared.UserProfileManager == null)
                throw new NotSupportedException("COFEShared.UserProfileManager is null.");
            if (COFEShared.UserProfileManager is IUserProfileManager2)
                return COFEShared.UserProfileManager as IUserProfileManager2;
            return null;
        }

        public static void RegisterUser(string userName, string password)
        {
            var upm = checkUpm();
            if (upm != null)
                upm.CreateUser(userName, password);
        }

        public static void UnregisterUser(string userName)
        {
            var upm = checkUpm();
            if (upm != null)
                upm.DeleteUser(userName);
        }

        public static void Authorize(string userName, string volumeId)
        {
            var upm = checkUpm();
            if (upm != null)
            {
                userName = userName.ToLower();
                var user = upm.Users.FirstOrDefault(u => u.UserName == userName);
                if (user == null)
                    throw new ArgumentException("User not found.");

                user.Volumes.RegisterVolume(volumeId);
            }
            
        }

        public static void RegisterVolume(string factoryId, string volumeId, string paramString, VolumeAccessMode accessMode = VolumeAccessMode.All)
        {
            COFEShared.VolumeRegistrar.RegisterVolume(factoryId, volumeId, paramString, accessMode);
        }

        public static void RegisterVolume(string factoryId)
        {
            COFEShared.VolumeRegistrar.RegisterVolume(factoryId, factoryId, VolumeAccessMode.All);
        }

        public static void UnregisterVolume(string volumeId)
        {
            COFEShared.VolumeRegistrar.RemoveVolume(volumeId);
        }


        #endregion

        #region Public Property

        public static string[] Factories { get { return COFEShared.VolumeRegistrar.Factories.Keys.ToArray(); } }
        public static string[] Volumes { get { return COFEShared.VolumeRegistrar.Volumes.Keys.ToArray(); } }
        public static string[] Users
        {
            get
            {
                return COFEShared.UserProfileManager is IUserProfileManager2 ?
                    (from u in (COFEShared.UserProfileManager as IUserProfileManager2).Users select u.UserName).ToArray() :
                    new string[] { };
            }
        }

        #endregion
    }
}
